package com.luomuchen.demo02.servic.impl;

import com.luomuchen.demo02.bean.Oop;
import com.luomuchen.demo02.mapper.OopMapper;
import com.luomuchen.demo02.servic.OopService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;

@Service
@Slf4j
public class OopServiceImpl implements OopService {
    @Resource
    private OopMapper oopMapper;
    @Autowired
    Redisson redisson;
    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Override
    public void add(Oop oop) {
        oopMapper.insert(oop);
    }

    @Override
    public Object getOopById(Integer id) {
        String key = "user:" + id;
        String lockKey = "lock:"+key;
        RLock lock = redisson.getLock(lockKey);
        lock.lock();//加锁
        Object oopObj = redisTemplate.opsForValue().get(key);
        try{
            if(oopObj == null){
                log.info("------------------查询数据库---------------------");
                Oop oop = oopMapper.selectByPrimaryKey(id);
                redisTemplate.opsForValue().set(key, oop);
                return oop;
            }
            else{
                log.info("<<<<<<<<<<<<<<<<<<<<<查询redis>>>>>>>>>>>>>>>>>>>>>");
            }
        }finally {
            lock.unlock();
        }
        return oopObj;
    }
}
